﻿@model ShipmentModel
@using Nop.Core.Domain.Tax;
@using Nop.Core.Domain.Catalog;
@{
    //page title
    ViewBag.Title = string.Format(T("Admin.Orders.Shipments.AddNew.Title").Text, Model.OrderId);
    Html.AddCssFileParts("~/subsites/Administration/Content/orders.css");
}
@helper RenderProduct(ShipmentModel.ShipmentOrderProductVariantModel item)
{
    <div class="shipmentProduct" data-id="@item.OrderProductVariantId" data-qty="@item.QuantityToAdd">
        <table>
            <tr>
                @if (!String.IsNullOrEmpty(item.ProductPictureUrl))
                {
                    <td>
                        <img src="@item.ProductPictureUrl" />
                    </td>
                }
                <td>
                    @*<a href="@Url.Action("Edit", "ProductVariant", new { id = item.ProductVariantId })">@item.FullProductName</a>*@
                <div class="text">@item.FullProductName</div>
                <div class="text">
                    @if (!String.IsNullOrEmpty(item.AttributeInfo))
                    {
                        @Html.Raw(item.AttributeInfo)
                    }
                </div>
            </td>
            <td class="qty">
                @item.QuantityToAdd
            </td>
        </tr>
    </table>
</div>
}

<div class="section-header">
    <div class="title">
        <img src="@Url.Content("~/subsites/Administration/Content/images/ico-sales.png")" alt="" />
        @string.Format(T("Admin.Orders.Shipments.AddNew.Title").Text, Model.OrderId) @Html.ActionLink("(" + T("Admin.Orders.Shipments.BackToOrder") + ")", "Edit", new { id = Model.OrderId })
    </div>
    <div class="options">
        @*<input type="submit" name="save" class="t-button" value="@T("Admin.Common.Save")" />*@
        @*<input type="submit" name="save-continue" class="t-button" value="@T("Admin.Common.SaveContinue")" />*@
        @*@Html.ActionLink("Print Picking", "PrintPicking", new { orderId = Model.OrderId }, new { @class = "t-button" })*@
        <a href="javascript:void(0)" class="finishSubmit t-button">Submit</a>
        @Html.ActionLink("Cancel", "AddShipment", new { orderId = Model.OrderId }, new { @class = "t-button" })
        @*if (Model.CurrentPackage == null)
            {
                <input type="submit" name="btnSubmit" class="t-button" value="Submit" />
            }*@
    </div>
    <div class="clear"></div>
</div>

@Html.ValidationSummary(false)

@Html.HiddenFor(model => model.Id)
<script>
    var _item, packageCount = 0, currentPackage = 0, packageObject = {}, allItemObject = {}, remainingItemObject = {}, dimensionUnits = {}, weightUnits = {}, maxQtyInput, moveItemId, actionType, pendingAction;
    var attribute1 = "", attribute2 = "", attribute3 = "";
    @foreach (var w in Model.AvaliableWeightMeasure)
    {
        <text>weightUnits['@w.Value'] = '@w.Text';</text>
    }
    @foreach (var d in Model.AvaliableDimensionMeasure)
    {
        <text>dimensionUnits['@d.Value'] = '@d.Text';</text>
    }
    $(document).ready(function () {
        /* Populate objects */
        $(".orderShipmentsRef .shipmentProduct").each(function () {
            allItemObject[$(this).attr("data-id")] = parseInt($(this).attr("data-qty"));
        });
        $(".orderProductsRemaining .shipmentProduct").each(function () {
            remainingItemObject[$(this).attr("data-id")] = parseInt($(this).attr("data-qty"));
        });
        $("#IsVertical").attr("checked", false);

        /* jQuery UI instances */
        var qtyDialog = $("#desiredQuantity").dialog({
            autoOpen: false,
            title: "Quantity",
            height: 150,
            width: 150,
            modal: true,
            open: function (event, ui) {
                $(".desiredQtyTable").appendTo($("#desiredQuantity"));
            },
            buttons: {
                "Ok": confirmQty,
                Cancel: function () {
                    qtyDialog.dialog("close");
                }
            },
            close: function () {
                _item = null;
            }
        }), measureDialog = $('#packageMeasurement').dialog({
            autoOpen: false,
            title: "Package Measurements",
            height: 150,
            width: 150,
            modal: true,
            open: function (event, ui) {
                if (currentPackage in packageObject && "m" in packageObject[currentPackage] && !$.isEmptyObject(packageObject[currentPackage]["m"])) {
                    if (packageObject[currentPackage]["m"]["isVertical"]) {
                        $("#IsVertical").attr("checked", true);
                    } else {
                        $("#IsVertical").attr("checked", false);
                    }
                    if (packageObject[currentPackage]["m"]["isFragile"]) {
                        $("#IsFragile").attr("checked", true);
                    } else {
                        $("#IsFragile").attr("checked", false);
                    }
                    if (packageObject[currentPackage]["m"]["isDangerous"]) {
                        $("#IsDangerous").attr("checked", true);
                    } else {
                        $("#IsDangerous").attr("checked", false);
                    }
                    //only for third party shipping options
                    $("#packageLength").val(packageObject[currentPackage]["m"]["length"]);
                    $("#packageWidth").val(packageObject[currentPackage]["m"]["width"]);
                    $("#packageHeight").val(packageObject[currentPackage]["m"]["height"]);
                    $("#packageWeight").val(packageObject[currentPackage]["m"]["weight"]);
                    //if (packageObject[currentPackage]["m"]["isStandardPackage"]) {
                    //    $("#isStandard").attr("checked", true);
                    //} else {
                    //    $("#isStandard").attr("checked", false);
                    //}
                } else {
                    $("#IsVertical").attr("checked", true);
                    $("#IsFragile").attr("checked", true);
                    $("#IsDangerous").attr("checked", true);
                    $("#packageWeight, #packageWidth, #packageHeight, #packageLength").val();
                    //$("#isStandard").attr("checked", true);
                }
                $("#desiredQtyInput").select();
            },
            buttons: {
                "Ok": confirmMeasurement
            },
            close: function (event, ui) {
                $(".desiredQtyTable").appendTo($("#desiredQuantity"));
            }
        }), textDialog = $('<div class="textDialog"></div>').dialog({
            autoOpen: false,
            modal: true,
            title: "Notice"
        });
        $(".shipmentProduct").draggable({
            revert: true,
            revertDuration: 0,
            containment: "#orderShipments",
            cursor: "move",
            cursorAt: { top: 50, left: 50 },
            helper: "clone"
        }).live("click", function () {
            if ($(this).hasClass("active")) {
                $(".shipmentProduct").removeClass("active");
            } else {
                $(".shipmentProduct").removeClass("active");
                $(this).addClass("active");
            }
        });
        $(".orderCurrentShipment").droppable({
            accept: ".orderProductsRemaining .shipmentProduct",
            hoverClass: "highlight",
            drop: function (event, ui) {
                if (currentPackage == 0) {
                    moveProduct(ui.draggable, "addToShipment", true);
                } else {
                    moveProduct(ui.draggable, "addToShipment");
                }
            }
        });
        $(".orderProductsRemaining").droppable({
            accept: ".orderCurrentShipment .shipmentProduct",
            hoverClass: "highlight",
            drop: function (event, ui) {
                moveProduct(ui.draggable, "removeFromShipment");
            }
        });
        $(".addNewPackage").droppable({
            accept: ".orderProductsRemaining .shipmentProduct",
            hoverClass: "highlightPlus",
            drop: function (event, ui) {
                if (!$(".plusButton").hasClass("disabled")) {
                    if (currentPackage != 0 && currentPackage in packageObject && (!("i" in packageObject[currentPackage]) || $.isEmptyObject(packageObject[currentPackage]["i"]))) {
                    } else {
                        moveProduct(ui.draggable, "addToShipment", true);
                    }
                }
            }
        });
        /* Button events */
        $(".shipmentPackage").live("click", function () {
            if (parseInt($(this).attr("data-id")) != currentPackage) {
                var toNumber = parseInt($(this).attr("data-id"));
                if ($.isEmptyObject(packageObject[currentPackage]) || !("i" in packageObject[currentPackage]) || $.isEmptyObject(packageObject[currentPackage]["i"])) {
                    textDialog.html("You cannot edit other packages if your current package is empty. Do you wish to remove the current package?").dialog({
                        buttons: {
                            "Ok": function () {
                                textDialog.dialog("close");
                                removePackage(toNumber);
                            },
                            Cancel: function () {
                                textDialog.dialog("close")
                            }
                        }
                    }).dialog("open");
                } else {
                    $(".shipmentPackage").removeClass("active");
                    $(this).addClass("active");
                    switchToPackage(parseInt($(this).attr("data-id")));
                }
            }
        });
        $(".enterPackageMeasurement").live("click", function () {
            pendingAction = null;
            measureDialog.dialog("open");
        });
        $(".removePackage").live("click", function () {
            if (!$(this).hasClass("disabled")) {
                if (currentPackage in packageObject) {
                    if ("i" in packageObject[currentPackage] && !$.isEmptyObject(packageObject[currentPackage]["i"])) {
                        // has item in current package
                        textDialog.html("Items have already been added to this package. Remove this package and return the items to the unpackaged list?").dialog({
                            buttons: {
                                "Ok": function () {
                                    textDialog.dialog("close");
                                    removePackage();

                                },
                                Cancel: function () {
                                    textDialog.dialog("close");
                                }
                            }
                        }).dialog("open");
                    } else {
                        removePackage();
                    }
                } else {
                    if (currentPackage == packageCount) {
                        packageCount--;
                        $(".orderShipmentsList .shipmentPackage[data-id=" + currentPackage + "]").remove();
                        switchToPackage(currentPackage - 1);
                    }
                }
            }
        });
        $(".resetPackages").live("click", function () {
            if (!$(this).hasClass("disabled")) {
                for (var i in packageObject) {
                    delete packageObject[i];
                }
                for (var i in remainingItemObject) {
                    delete remainingItemObject[i];
                }
                $.extend(remainingItemObject, allItemObject);
                $(".orderCurrentShipment .items, .orderProductsRemaining .items").empty();
                for (var i in remainingItemObject) {
                    var clone = $(".orderShipmentsRef .shipmentProduct[data-id=" + i + "]").clone().draggable({
                        revert: true,
                        revertDuration: 0,
                        containment: "#orderShipments",
                        cursor: "move",
                        cursorAt: { top: 50, left: 50 },
                        helper: "clone"
                    }).appendTo($(".orderProductsRemaining .items"));
                    clone.attr("data-qty", remainingItemObject[i]).find(".qty").text(remainingItemObject[i]);
                }
                $(".orderShipmentsList").empty();
                packageCount = 0;
                currentPackage = 0;
                reinitializeForm();
            }
        });
        $(".finishSubmit").live("click", function () {
            if (!$(this).hasClass("disabled")) {
                if (!$.isEmptyObject(packageObject)) {
                    if (!("m" in packageObject[currentPackage])) {
                        pendingAction = "finishSubmit";
                        measureDialog.dialog("open");
                    } else {
                        submitForm();
                    }
                }
            }
        });
        $(".plusButton").live("click", function () {
            if (!$(this).hasClass("disabled")) {
                switchToPackage(currentPackage + 1);
                measureDialog.dialog("open");
            }
        });
        $(".t-iconWrapper.next").live("click", function () {
            slidePackagePager(0, 8);
        });
        $(".t-iconWrapper.prev").live("click", function () {
            slidePackagePager(0, -8);
        });
        reinitializeForm();
        function slidePackagePager(toNumber, toCount) {
            var firstPos = parseInt($(".orderShipmentsList").css("left"));
            if (isNaN(parseInt($(".orderShipmentsList").css("left")))) {
                firstPos = 0;
            }
            var currentFirst = (-firstPos / $(".shipmentPackage").outerWidth()) + 1, targetFirst;
            if (toCount != null) {
                if (currentFirst + toCount < 1) {
                    targetFirst = 0;
                } else if (currentFirst + toCount > $(".shipmentPackage").length - 8) {
                    targetFirst = $(".shipmentPackage").length - 8;
                } else {
                    targetFirst = currentFirst + toCount - 1;
                }
            }
            $(".orderShipmentsList").stop().animate({ left: -$(".shipmentPackage").outerWidth() * targetFirst });
        }

        /* Supporting functions */
        function switchToPackage(packageNumber) {
            $(".orderCurrentShipment .controls input, .orderProductsRemaining .controls input, .finishSubmit, .plusButton").addClass("disabled");
            $(".orderProductsRemaining, .orderCurrentShipment").removeClass("empty noPackage");
            if (!$(".shipmentPackage[data-id=" + packageNumber + "]").length) {
                $(".orderShipmentsList").append('<div class="shipmentPackage" data-id="' + packageNumber + '">' + packageNumber + '</div>');
                packageCount += 1;
            }
            $(".shipmentPackage").removeClass("active");
            $(".shipmentPackage[data-id=" + packageNumber + "]").addClass("active");
            $(".orderCurrentShipment .items .shipmentProduct").wrapAll('<div class="oldItems" />');
            if (!$(".orderCurrentShipment .items .oldItems").length) {
                $(".orderCurrentShipment .items").append('<div class="oldItems" />');
            }
            $(".orderCurrentShipment .oldItems").after('<div class="newItems" />');
            var posX;
            if (packageNumber >= currentPackage) {
                posX = $(".orderCurrentShipment").width();
            } else {
                posX = -$(".orderCurrentShipment").width();
            }

            // Find package items
            if (packageNumber in packageObject && !$.isEmptyObject(packageObject[packageNumber]["i"])) {
                for (var i in packageObject[packageNumber]["i"]) {
                    if (typeof packageObject[packageNumber]["i"][i] != "undefined") {
                        var clone = $(".orderShipmentsRef .shipmentProduct[data-id=" + i + "]").clone().draggable({
                            revert: true,
                            revertDuration: 0,
                            containment: "#orderShipments",
                            cursor: "move",
                            cursorAt: { top: 50, left: 50 },
                            helper: "clone"
                        }).appendTo($(".orderCurrentShipment .newItems"));
                        clone.attr("data-qty", packageObject[packageNumber]["i"][i]).find(".qty").text(packageObject[packageNumber]["i"][i]);
                    }
                }
            }
            currentPackage = packageNumber;

            // Fill in measurement if not set
            if (!(currentPackage in packageObject)) {
                packageObject[currentPackage] = {};
            }
            if (currentPackage in packageObject && $.isEmptyObject(packageObject[currentPackage]["m"])) {
                packageObject[currentPackage]["m"] = {
                    length: $("#packageLength").val(),
                    width: $("#packageWidth").val(),
                    height: $("#packageHeight").val(),
                    weight: $("#packageWeight").val(),
                    dimensionUnit: $(".DimensionMeasureId:checked").val(),//$("#dimensionUnit").val(),
                    weightUnit: $(".WeightMeasureId:checked").val(),//$("#weightUnit").val(),
                    //isStandardPackage: $("#isStandard").is(":checked")
                    isVertical: $("#IsVertical").is(":checked"),
                    isFragile: $("#IsFragile").is(":checked"),
                    isDangerous: $("#IsDangerous").is(":checked")
                }
            }

            // Animate
            $(".orderCurrentShipment").css("overflow", "hidden");
            $(".orderCurrentShipment .oldItems").stop().animate({ "left": -posX });
            $(".orderCurrentShipment .newItems").stop().css({ "left": posX, "top": 0 }).animate({ "left": 0 }, function () {
                $(".orderCurrentShipment .oldItems").remove();
                $(".orderCurrentShipment .newItems").children().unwrap(".newItems");
                $(".orderCurrentShipment .newItems").remove();
                $(".orderCurrentShipment").css("overflow", "visible");
                reinitializeForm();
            });
            $(".currentPackageNumber").text(packageNumber);

        }
        function removePackage(toNumber) {
            var last = Object.keys(packageObject).length;
            if (currentPackage in packageObject && "i" in packageObject[currentPackage] && !$.isEmptyObject(packageObject[currentPackage]["i"])) {
                for (var i in packageObject[currentPackage]["i"]) {
                    if (i in remainingItemObject) {
                        remainingItemObject[i] = parseInt(remainingItemObject[i]) + parseInt(packageObject[currentPackage]["i"][i]);
                    } else {
                        remainingItemObject[i] = parseInt(packageObject[currentPackage]["i"][i]);
                    }
                }
                $(".orderProductsRemaining .items").empty();
                for (var i in remainingItemObject) {
                    var clone = $(".orderShipmentsRef .shipmentProduct[data-id=" + i + "]").clone().draggable({
                        revert: true,
                        revertDuration: 0,
                        containment: "#orderShipments",
                        cursor: "move",
                        cursorAt: { top: 50, left: 50 },
                        helper: "clone"
                    }).appendTo($(".orderProductsRemaining .items"));
                    clone.attr("data-qty", remainingItemObject[i]).find(".qty").text(remainingItemObject[i]);
                }
            }
            for (var i in packageObject) {
                if (parseInt(i) > currentPackage) {
                    $.extend(packageObject[parseInt(i) - 1], packageObject[i]);
                }
            }
            delete packageObject[last];
            packageCount--;
            $(".orderShipmentsList .shipmentPackage::last-child").remove();
            if (toNumber != null) {
                switchToPackage(toNumber);
            } else {
                if (currentPackage in packageObject) {
                    switchToPackage(currentPackage);
                } else {
                    if (currentPackage == 1) {
                        currentPackage = 0;
                        reinitializeForm();
                    } else {
                        switchToPackage(currentPackage - 1);
                    }
                }
            }
        }
        function moveProduct(item, type, createNew) {
            _item = item;
            var id = item.attr("data-id");
            var availableQty = item.attr("data-qty");
            $(".shipmentProduct").removeClass("active");
            maxQtyInput = availableQty;
            moveItemId = id;
            actionType = type;
            $("#desiredQtyInput").attr({ max: availableQty, min: 0 }).val(availableQty);
            if (createNew) {
                if (availableQty > 1) {
                    $("#packageMeasurement").prepend($(".desiredQtyTable"));
                }
                pendingAction = "moveProductToNewPackage";
                confirmMeasurement();
                measureDialog.dialog("open");
            } else {
                //Find if more than one is allowed to change
                if (availableQty > 1) {
                    showQtyForm();
                } else {
                    confirmQty();
                }
            }
        }
        function showQtyForm() {
            qtyDialog.dialog("open");
            $("#desiredQtyInput").attr({ max: maxQtyInput, min: 0 }).val(maxQtyInput).select();
        }
        function confirmQty() {
            var qty = parseInt($("#desiredQtyInput").val()), newQty, targetItem;
            if (!(currentPackage in packageObject)) {
                packageObject[currentPackage] = {};
            }
            if (!("i" in packageObject[currentPackage])) {
                packageObject[currentPackage]["i"] = {};
            }
            if (!("m" in packageObject[currentPackage])) {
                packageObject[currentPackage]["m"] = {};
            }
            if (actionType == "addToShipment") {
                // Add from order to shipment
                if (moveItemId in packageObject[currentPackage]["i"]) {
                    newQty = qty + packageObject[currentPackage]["i"][moveItemId];
                } else {
                    newQty = qty;
                }
                remainingItemObject[moveItemId] = parseInt(remainingItemObject[moveItemId]) - qty;
                packageObject[currentPackage]["i"][moveItemId] = newQty;
                if (remainingItemObject[moveItemId] == 0) {
                    delete remainingItemObject[moveItemId];
                }
                // Manipulate DOM
                if (pendingAction != "moveProductToNewPackage") {
                    targetItem = $(".orderCurrentShipment .shipmentProduct[data-id=" + moveItemId + "]");
                    if (!targetItem.length) {
                        targetItem = $(".orderShipmentsRef .shipmentProduct[data-id=" + moveItemId + "]").clone().draggable({
                            revert: true,
                            revertDuration: 0,
                            containment: "#orderShipments",
                            cursor: "move",
                            cursorAt: { top: 50, left: 50 },
                            helper: "clone"
                        }).appendTo($(".orderCurrentShipment .items"));
                    }
                    targetItem.attr("data-qty", newQty).find(".qty").text(newQty);
                }
                if (qty == maxQtyInput) {
                    _item.remove();
                } else {
                    _item.attr("data-qty", parseInt(_item.attr("data-qty")) - qty).find(".qty").text(_item.attr("data-qty"));
                }
                $(".orderCurrentShipment").removeClass("empty noPackage");
            } else {
                // Move from shipment to order
                newQty = packageObject[currentPackage]["i"][moveItemId] - qty;
                packageObject[currentPackage]["i"][moveItemId] = newQty;
                if (moveItemId in remainingItemObject) {
                    remainingItemObject[moveItemId] = parseInt(remainingItemObject[moveItemId]) + qty;
                } else {
                    remainingItemObject[moveItemId] = qty;
                }

                var targetQty;
                targetItem = $(".orderProductsRemaining .shipmentProduct[data-id=" + moveItemId + "]");
                if (!targetItem.length) {
                    targetItem = $(".orderShipmentsRef .shipmentProduct[data-id=" + moveItemId + "]").clone().draggable({
                        revert: true,
                        revertDuration: 0,
                        containment: "#orderShipments",
                        cursor: "move",
                        cursorAt: { top: 50, left: 50 },
                        helper: "clone"
                    }).appendTo($(".orderProductsRemaining .items"));
                    targetQty = qty;
                } else {
                    targetQty = parseInt(targetItem.attr("data-qty")) + qty;
                }
                targetItem.attr("data-qty", targetQty).find(".qty").text(targetQty);

                if (packageObject[currentPackage]["i"][moveItemId] == 0) {
                    delete packageObject[currentPackage]["i"][moveItemId];
                    _item.remove();
                } else {
                    _item.attr("data-qty", newQty).find(".qty").text(newQty);
                }
            }
            maxQtyInput = null;
            moveItemId = null;
            actionType = null;
            if ($.isEmptyObject(packageObject[currentPackage]["i"]) && $.isEmptyObject(packageObject[currentPackage]["m"])) {
                delete packageObject[currentPackage];
            }
            qtyDialog.dialog("close");
            reinitializeForm();
            $('body').css("cursor", "default");
            if ($.isEmptyObject(remainingItemObject)) {
                textDialog.html("All items have been added to packages. Would you like to submit your packages for the shipment?").dialog({
                    buttons: {
                        "Ok": function () {
                            submitForm();
                            textDialog.dialog("close");
                        },
                        Cancel: function () {
                            textDialog.dialog("close");
                        }
                    }
                });
            }
        }
        function confirmMeasurement() {
            if (pendingAction == "moveProductToNewPackage") {
                currentPackage += 1;
            }
            if (!(currentPackage in packageObject)) {
                packageObject[currentPackage] = {}
            }
            packageObject[currentPackage]["m"] = {
                length: $("#packageLength").val(),
                width: $("#packageWidth").val(),
                height: $("#packageHeight").val(),
                weight: $("#packageWeight").val(),
                dimensionUnit: $(".DimensionMeasureId:checked").val(),//$("#dimensionUnit").val(),
                weightUnit: $(".WeightMeasureId:checked").val(),//$("#weightUnit").val(),
                //isStandardPackage: $("#isStandard").is(":checked")
                isVertical: $("#IsVertical").is(":checked"),
                isFragile: $("#IsFragile").is(":checked"),
                isDangerous: $("#IsDangerous").is(":checked")
            }
            if (pendingAction == "nextPackage") {
                switchToPackage(parseInt($(".shipmentPackage.active").attr("data-id")) + 1);
            } else if (pendingAction == "finishSubmit") {
                submitForm();
            } else if (pendingAction == "moveProductToNewPackage") {
                confirmQty();
                switchToPackage(currentPackage);
            } else {
                reinitializeForm();
            }
            pendingAction = null;
            measureDialog.dialog("close");
        }
        function submitForm() {
            var n = 0;
            for (var i in packageObject) {
                if (!$.isEmptyObject(packageObject[i]["i"])) {
                    var productnumber = 0;
                    for (var j in packageObject[i]["i"]) {
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].Products[' + productnumber + '].OrderProductVariantId" value="' + j + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].Products[' + productnumber + '].QuantityToAdd" value="' + packageObject[i]["i"][j] + '" />');
                        productnumber++;
                    }
                    var m = 0;
                    if (!$.isEmptyObject(packageObject[i]["m"])) {
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].IsVertical" value="' + packageObject[i]["m"].isVertical + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].IsFragile" value="' + packageObject[i]["m"].isFragile + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].IsDangerous" value="' + packageObject[i]["m"].isDangerous + '" />');
                        //$("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].IsStandard" value="' + packageObject[i]["m"].isStandardPackage + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].DimensionMeasureId" value="' + packageObject[i]["m"].dimensionUnit + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].WeightMeasureId" value="' + packageObject[i]["m"].weightUnit + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].length" value="' + packageObject[i]["m"].length + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].width" value="' + packageObject[i]["m"].width + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].height" value="' + packageObject[i]["m"].height + '" />');
                        $("#shipmentFormValues").append('<input type="hidden" name="Packages[' + n + '].weight" value="' + packageObject[i]["m"].weight + '" />');
                    }
                    n++;
                }
            }
            $("form").submit();
            reinitializeForm();
        }
        function reinitializeForm() {
            $(".orderCurrentShipment .controls input, .orderProductsRemaining .controls input, .finishSubmit, .plusButton").removeClass("disabled");
            $(".orderProductsRemaining, .orderCurrentShipment").removeClass("empty noPackage");
            if ($.isEmptyObject(packageObject) || ($.isEmptyObject(packageObject[currentPackage]) && packageCount == 1)) {
                $(".resetPackages").addClass("disabled");
            }
            if (!$.isEmptyObject(remainingItemObject)) {
                $(".finishSubmit").addClass("disabled");
            } else {
                $(".orderProductsRemaining").addClass("empty");
            }
            if (currentPackage != 0) {
                if ($.isEmptyObject(packageObject[currentPackage]) || $.isEmptyObject(remainingItemObject) || !("i" in packageObject[currentPackage]) || ("i" in packageObject[currentPackage] && $.isEmptyObject(packageObject[currentPackage]["i"]))) {
                    $(".plusButton").addClass("disabled");
                }
                if ($.isEmptyObject(packageObject[currentPackage]) || !("i" in packageObject[currentPackage]) || ("i" in packageObject[currentPackage] && $.isEmptyObject(packageObject[currentPackage]["i"]))) {
                    $(".orderCurrentShipment").addClass("empty");
                }
            } else {
                $(".orderCurrentShipment").addClass("noPackage");
            }
            if (currentPackage == 1 && packageCount == 1) {
                $(".removePackage").addClass("disabled");
            }
            var c = 0;
            for (var i in remainingItemObject) {
                c += remainingItemObject[i];
            }
            if (c == 1) {
                $(".orderProductsRemaining .messages").html("<span>There is 1 item left unpackaged.</span>");
            } else if (c > 1) {
                $(".orderProductsRemaining .messages").html("<span>There are " + c + " items left unpackaged.</span>");
            } else {
                $(".orderProductsRemaining .messages").html("<span>All items have been packaged.</span>");
            }
            if (currentPackage == 0) {
                $(".orderCurrentShipment h2, .orderCurrentShipment .controls, .orderCurrentShipment .messages").hide();
            } else {
                $(".orderCurrentShipment h2, .orderCurrentShipment .controls, .orderCurrentShipment .messages").show();
                $(".orderCurrentShipment h2").text("Items in Package #" + currentPackage);
                if (currentPackage in packageObject && "m" in packageObject[currentPackage] && !$.isEmptyObject(packageObject[currentPackage]["m"])) {
                    if (packageObject[currentPackage]["m"]["isVertical"] == true) {
                        attribute1 = " VH ";
                    } else {
                        attribute1 = ""
                    }
                    if (packageObject[currentPackage]["m"]["isDangerous"] == true) {
                        attribute2 = " DG ";
                    } else {
                        attribute2 = ""
                    }
                    if (packageObject[currentPackage]["m"]["isFragile"] == true) {
                        attribute3 = " FG ";
                    } else {
                        attribute3 = ""
                    }
                    $(".orderCurrentShipment .messages").html("<span>This is an @T("Messages.Order.Product(s).OnlineShoppingOrder")</span>" + attribute1 + attribute2 + attribute3);
                    if (packageObject[currentPackage]["m"]["isStandardPackage"] != true && !$.isEmptyObject(packageObject[currentPackage]["m"]["length"])) {
                        var dimensionUnitText = dimensionUnits[packageObject[currentPackage]["m"]['dimensionUnit']];
                        var weightUnitText = weightUnits[packageObject[currentPackage]["m"]['weightUnit']];
                        $(".orderCurrentShipment .messages").html("<span>Package measurement: " + packageObject[currentPackage]["m"]["length"] + dimensionUnitText + " x " + packageObject[currentPackage]["m"]["width"] + dimensionUnitText + " x " + packageObject[currentPackage]["m"]["height"] + dimensionUnitText + " " + packageObject[currentPackage]["m"]["weight"] + weightUnitText);
                    } else {
                        //$(".orderCurrentShipment .messages").html("<span>This is a @T("Logistics.Order.Package.Size.Letter").</span>");
                    }
                } else {
                    $(".orderCurrentShipment .messages").html("<span>Please enter measurements of this package.</span>");
                }
            }

            if ($(".shipmentPackage").length > 8) {
                $(".t-iconWrapper").show();
                $(".orderShipmentsList").css("width", $(".shipmentPackage").length * $(".shipmentPackage").outerWidth(true));
            } else {
                $(".t-iconWrapper").hide();
            }
        }

    });

</script>
<div id="orderShipments">
    @using (Html.BeginForm())
    {
        <input type="hidden" name="ShipmentSubmit" value="ShipmentSubmit" />
        <div id="shipmentFormValues"></div>
        @Html.HiddenFor(model => model.IsThirdPartyShippingOption)
        @Html.HiddenFor(model => model.ShippingRateComputationMethodSystemName)
    }
    <div class="orderShipmentTop">
        <div class="shipmentListTitle">Packages: </div>
        <div class="t-iconWrapper prev"><div class="t-icon t-arrow-prev"></div></div>
        <div class="orderShipmentsListContainer">
            <div class="orderShipmentsList">
                @if (Model.Packages.Count >= 1)
                {
                    int i = 0;
                    foreach (var package in Model.Packages)
                    {
                        <div class="shipmentPackage" data-id="@i">@i</div>
                        i++;
                    }
                }
            </div>
        </div>
        <div class="t-iconWrapper next"><div class="t-icon t-arrow-next"></div></div>
        <div class="clear"></div>
    </div>
    <div class="clear"></div>
    <div class="orderShipmentsRight">
        <div class="orderCurrentShipment">
            <h2></h2>
            <div class="items">
                @if (Model.Packages != null && Model.Packages.Count > 0)
                {
                    for (int i = 0; i < Model.Packages.First().Products.Count; i++)
                    {
                        @RenderProduct(Model.Packages.First().Products[i]);
                    }
                }
            </div>
            <div class="emptyMessage">
                <div class="dropdownIcon"></div>
                <div>Drop items here to add to a package.</div>
            </div>
            <div class="messages"></div>
            <div class="controls">
                <input type="button" class="enterPackageMeasurement" value="Package Measurements">
                <input type="button" class="removePackage" value="Remove Package" />
            </div>
        </div>
    </div>

    <div class="orderShipmentsLeft">
        <div class="orderProductsRemaining">
            <h2>Items Not Yet Packaged</h2>
            <div class="items">
                @if (Model.UnpackagedProducts != null && Model.UnpackagedProducts.Count > 0)
                {
                    for (int i = 0; i < Model.UnpackagedProducts.Count; i++)
                    {
                        @RenderProduct(Model.UnpackagedProducts[i]);
                    }
                }
            </div>
            <!--<div class="emptyMessage">
                <div class="dropdownIcon"></div>
                <div>Drop items here to remove them from the package.</div>
            </div>-->
            <div class="messages"></div>
            <div class="controls">
                <input type="button" class="resetPackages" value="Reset All Packages" />

            </div>
        </div>
    </div>

    <div class="orderShipmentsCenter"><div class="addNewPackage"><div class="plusButton">+</div></div></div>
    <div class="orderShipmentsRef">
        @if (Model.Products != null)
        {
            for (int i = 0; i < Model.Products.Count; i++)
            {
                @*
                    var item = Model.Products[i];
                    <div class="shipmentProduct" data-id="@item.ProductVariantId" data-qty="@item.QuantityToAdd">
                        @Html.HiddenFor(model => model.Products[i].OrderProductVariantId)
                        @Html.HiddenFor(model => model.Products[i].ProductVariantId)
                        @Html.HiddenFor(model => model.Products[i].FullProductName)
                        @Html.HiddenFor(model => model.Products[i].AttributeInfo)
                        @Html.HiddenFor(model => model.Products[i].Sku)
                        @Html.HiddenFor(model => model.Products[i].QuantityOrdered)
                    </div>
                *@
                <div class="productReference" data-id="@Model.Products[i].OrderProductVariantId">
                    @Html.HiddenFor(model => model.Products[i].OrderProductVariantId)
                    @Html.HiddenFor(model => model.Products[i].ProductVariantId)
                    @Html.HiddenFor(model => model.Products[i].FullProductName)
                    @Html.HiddenFor(model => model.Products[i].ProductPictureUrl)
                    @Html.HiddenFor(model => model.Products[i].AttributeInfo)
                    @Html.HiddenFor(model => model.Products[i].Sku)
                    @Html.HiddenFor(model => model.Products[i].QuantityOrdered)
                    @RenderProduct(Model.Products[i]);
                </div>
            }
        }

    </div>
    <div class="clear"></div>
    <div id="desiredQuantity">
        <table class="desiredQtyTable">
            <tbody>
                <tr>
                    <td><label>Item Quantity: </label></td>
                    <td><input type="number" id="desiredQtyInput" value="0" /></td>
                </tr>
            </tbody>
        </table>
    </div>

    <div id="packageMeasurement">
        @if (Model.IsThirdPartyShippingOption)
        {
            <input type="checkbox" id="isStandard" value="false" style="visibility: hidden" />
            <table>
                <tbody>
                    <tr>
                        <td><label>Dimension Unit: </label></td>
                        <td>
                            @foreach (var d in Model.AvaliableDimensionMeasure)
                            {
                                var dselected = d.Selected ? "selected" : "";
                                @Html.RadioButtonFor(model => model.DimensionMeasureId, d.Value, new { selected = dselected, id = "dimensionUnit", @class = "DimensionMeasureId" })
                                <label>@d.Text</label>
                                @*<input type="radio" id="dimensionUnit" value="@d.Value" @if (d.Selected) { <text> checked="checked" </text> } /> <span>@d.Text</span>*@
                            }
                        </td>
                    </tr>
                    <tr>
                        <td><label>Weight Unit: </label></td>
                        <td>
                            @foreach (var w in Model.AvaliableWeightMeasure)
                            {
                                var dselected = w.Selected ? "selected" : "";
                                @Html.RadioButtonFor(model => model.WeightMeasureId, w.Value, new { selected = dselected, id = "weightUnit", @class = "WeightMeasureId" })
                                <label>@w.Text</label>
                                @*<input type="radio" id="weightUnit" value="@w.Value" @if (w.Selected) { <text> checked="checked" </text> } /> <span>@w.Text</span>*@
                            }
                        </td>
                    </tr>
                </tbody>
            </table>
            <table>
                <tbody>
                    <tr><td>@Html.LabelFor(model => model.Length)</td><td><input type="number" step="0.01" id="packageLength" value="0" min="0" /></td></tr>
                    <tr><td>@Html.LabelFor(model => model.Width)</td><td><input type="number" step="0.01" id="packageWidth" value="0" min="0" /></td></tr>
                    <tr><td>@Html.LabelFor(model => model.Height)</td><td><input type="number" step="0.01" id="packageHeight" value="0" min="0" /></td></tr>
                    <tr><td>@Html.LabelFor(model => model.TotalWeight)</td><td><input type="number" step="0.01" id="packageWeight" value="0" min="0" /></td></tr>
                </tbody>
            </table>
        }
        else
        {

            <table>
                <tbody>
                    <tr><td>This is an @T("Messages.Order.Product(s).OnlineShoppingOrder")</td></tr>
                </tbody>
            </table>

            <table>
                <tbody>
                    <tr>
                        <td>
                            <input type="checkbox" id="IsVertical" />
                            <label for="IsVertical">@T("Logistics.Order.Package.IsVertical")?</label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="checkbox" id="IsFragile" />
                            <label for="IsFragile">@T("Logistics.Order.Package.IsFragile")?</label>
                        </td>
                    </tr>
                    @*<tr>
                            <td>
                                <input type="checkbox" id="IsDangerous" />
                                <label for="IsDangerous">@T("Logistics.Order.Package.IsDangerous")?</label>
                            </td>
                        </tr>*@
                </tbody>
            </table>
        }

        @*<table>
        <tbody>
            <tr><td><input type="checkbox" id="isStandard" checked="checked" /> This is a @T("Logistics.Order.Package.Size.Letter")</td></tr>
        </tbody>
    </table>*@
    </div>
</div>
